package com.ygl.gateway.bean;

import com.alibaba.fastjson.JSONObject;
import com.ygl.gateway.config.AppConfig;
import com.ygl.gateway.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Slf4j
//@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AuthFilter implements GlobalFilter, Ordered  {
    private final JwtUtil jwtUtil;
    private final AppConfig appConfig;

    private String tokenKey = "token";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("认证---");

        ServerHttpRequest request = exchange.getRequest();
        final String method = request.getMethodValue();
        final String requestUri = request.getURI().getPath();
        if (HttpMethod.OPTIONS.matches(method) || matchUri(requestUri)) {
            return chain.filter(exchange);
        }
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst(tokenKey);
        if (token == null) {
            token = request.getQueryParams().getFirst(tokenKey);
        }
        ServerHttpResponse response = exchange.getResponse();
        Boolean valid = jwtUtil.validateToken(token);
        if (!valid) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            JSONObject message = new JSONObject();
            message.put("status", -1);
            message.put("data", "鉴权失败");
            byte[] bits = message.toJSONString().getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(bits);
            //指定编码，否则在浏览器中会中文乱码
            response.getHeaders().add("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);
            return response.writeWith(Mono.just(buffer));
        } else {
            Claims claims = jwtUtil.getClaimsFromToken(token);
            String userId = null;
            if (claims.get("userId") != null) {
                userId = String.valueOf(claims.get("userId"));
            }
            String tenantId = null;
            if (claims.get("tenantId") != null) {
                tenantId = String.valueOf(claims.get("tenantId"));
                exchange.getAttributes().put("tenantId", tenantId);
            }

        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * 匹配URI是否以什么打头
     * @param requestUri
     * @return
     */
    private boolean matchUri(String requestUri) {
        String[] split = appConfig.getStartWith().split(",");
        for (String s : split) {
            if (requestUri.startsWith(s)) {
                return true;
            }
        }
        return false;
    }
}
